package com.tianbing.adlottery.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.jubao.ejb.business.WebsiteBusiness;
import com.jubao.ejb.entity.Category;
import com.jubao.ejb.entity.GeneRelation;
import com.jubao.ejb.entity.Website;

/**
 * MultiActionController for the image list/upload UI.
 * 
 * @author Conan Chen
 * @since 2006.12.15
 */
public class WebsiteController extends MultiActionController {
	Logger logger = Logger.getLogger(WebsiteController.class.getName());

	private String jsonView;

	private WebsiteBusiness websiteBusiness;

	public ModelAndView addonAjaxGetRelateWebsite(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ModelAndView mv = new ModelAndView(jsonView);
		Map model = mv.getModel();
		String url = ServletRequestUtils.getStringParameter(request, "url", "http://www.baidu.com");

		//first, anyway, we register the website automatically
		url = cleanUrl(url); //we only support this kind of url: (http[s]*://[^/]*)(.*)
		logger.info("going to register url="+url);
		Website website = websiteBusiness.registerWebsite(url);
		if (website != null) {
			logger.info("successfully register url="+url+" website.sysId="+website.getSysId());
			int maxNum = 30;
			HashMap<String, Object> relatedWebsiteInfo = websiteBusiness.getRelatedWebsiteInfo(url, maxNum);

			JSONObject jsonObj = new JSONObject();

			List<Website> websites = (List<Website>) relatedWebsiteInfo.get("site");
			if (websites != null) {
				JSONArray jsonWebsiteList = new JSONArray();
				for (int i = 0; i < websites.size(); i++) {
					Website w = websites.get(i);
					//$retSite = array($site["sid"],$site["uri"],$site["name"],$site["searchpath"],$site["rsspath"],$site["ranking"]);
					JSONArray jsonWebsite = new JSONArray();
					jsonWebsite.add(w.getSysId());
					jsonWebsite.add(w.getId());
					jsonWebsite.add(w.getName()==null?"":w.getName());
					jsonWebsite.add(w.getSearchUrl()==null?"":w.getSearchUrl());
					jsonWebsite.add(w.getRssUrl()==null?"":w.getRssUrl());
					jsonWebsite.add(w.getRank()==null?0:w.getRank());
					jsonWebsiteList.add(jsonWebsite);
				}
				jsonObj.put("site", jsonWebsiteList);
			}

			List<GeneRelation> s2cs = (List<GeneRelation>) relatedWebsiteInfo.get("s2c");
			if (s2cs != null) {
				JSONArray jsonS2CList = new JSONArray();
				for (int i = 0; i < s2cs.size(); i++) {
					GeneRelation gr = s2cs.get(i);
					// $rets2c = array($s2c["sid"],$s2c["sitesid"],$s2c["catsid"]);
					JSONArray jsonS2C = new JSONArray();
					jsonS2C.add(gr.getSysId());
					jsonS2C.add(gr.getEntity().getSysId());
					jsonS2C.add(gr.getEntity2().getSysId());
					jsonS2CList.add(jsonS2C);
				}
				jsonObj.put("s2c", jsonS2CList);
			}

			List<Category> websitePrimaryCatTrail = (List<Category>) relatedWebsiteInfo.get("primarypath");
			if (websitePrimaryCatTrail != null) {
				JSONArray jsonCatList = new JSONArray();
				for (int i = 0; i < websitePrimaryCatTrail.size(); i++) {
					Category gr = websitePrimaryCatTrail.get(i);
					// $ret["path"][] = $cat["sid"]; 
					JSONArray jsonCat = new JSONArray();
					jsonCat.add(gr.getSysId());
					jsonCatList.add(jsonCat);
				}
				jsonObj.put("path", jsonCatList);
			}

			List<Category> websitePrimaryAreaCatTrail = (List<Category>) relatedWebsiteInfo.get("primaryareapath");
			if (websitePrimaryAreaCatTrail != null) {
				JSONArray jsonCatList = new JSONArray();
				for (int i = 0; i < websitePrimaryAreaCatTrail.size(); i++) {
					Category gr = websitePrimaryAreaCatTrail.get(i);
					// $ret["path"][] = $cat["sid"]; 
					JSONArray jsonCat = new JSONArray();
					jsonCat.add(gr.getSysId());
					jsonCatList.add(jsonCat);
				}
				jsonObj.put("areaPath", jsonCatList);
			}

			model.put("json_string", jsonObj.toString());
		}
		return mv;
	}

	static String cleanUrl(String purl) {
		String regex = "(http[s]*://[^/]*)(.*)";
		// Get a Matcher based on the target string.
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(purl);
		boolean b = m.matches();
		if (b)
			return m.group(1);
		else
			return "";
	}

	/**
	 * @param logger the logger to set
	 */
	public void setLogger(Logger logger) {
		this.logger = logger;
	}

	public void setJsonView(String jsonView) {
		this.jsonView = jsonView;
	}

	public void setWebsiteBusiness(WebsiteBusiness websiteBusiness) {
		this.websiteBusiness = websiteBusiness;
	}

}
